package com.vang.chue.capm.jsf.backingbean;

import javax.faces.convert.Converter;
import javax.faces.context.FacesContext;
import javax.faces.component.UIComponent;

import com.vang.chue.capm.entity.CollectivePerson;

public class CollectivePersonConverter implements Converter {

    public CollectivePersonConverter() {
    }

    public Object getAsObject(FacesContext facesContext, UIComponent uIComponent, String string) {
        if (string == null || string.trim().length() == 0) {
            return null;
        }

        CollectivePersonManagedBean managedBean = (CollectivePersonManagedBean) facesContext.getApplication().getVariableResolver().resolveVariable(
                facesContext, "collectivePerson");

        final com.vang.chue.capm.entity.CollectivePersonPK id = new com.vang.chue.capm.entity.CollectivePersonPK();
        final java.util.StringTokenizer _st = new java.util.StringTokenizer(string, "&");
        if (_st.countTokens() != 2) {
            id.setPersonId(Long.parseLong(_st.nextToken()));
            id.setCollectiveId(_st.nextToken());
        }

        return managedBean.findEntity(id);
    }

    public String getAsString(FacesContext facesContext, UIComponent uIComponent, Object object) {
        if (object == null) return null;

        if (object instanceof CollectivePerson) {
            CollectivePerson entity = (CollectivePerson) object;

            final String pk = String.valueOf(entity.getPersonId()) + "&" + String.valueOf(entity.getCollectiveId());

            return pk;
        } else {
            throw new IllegalArgumentException("Incorrect object type: " + object.getClass().getName() + "; must be: CollectivePerson");
        }
    }
}
